package com.atguigu.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.atguigu.yygh.cmn.listener.DictListener;
import com.atguigu.yygh.cmn.mapper.DictMapper;
import com.atguigu.yygh.cmn.service.DictService;
import com.atguigu.yygh.model.cmn.Dict;
import com.atguigu.yygh.vo.cmn.DictEeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
    @Autowired
    private DictListener dictListener;
//    @Autowired
//    private DictMapper dictMapper;

    //根据id查询子数据列表
    //redis中key值dict::id 故不重复
    @Cacheable(value = "dict")
    @Override
    public List<Dict> findDataChild(Long id) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", id);
        List<Dict> dicts = baseMapper.selectList(wrapper);
        //遍历查询当前层级数据list集合,得到每条数据对象
        //判断每条记录下面是否有子节点
        //如果有子节点 设置对象里面hasChildren是true
        for (int i = 0; i < dicts.size(); i++) {
            Dict dict = dicts.get(i);
            Long dictId = dict.getId();
            boolean isChild = findIsChild(dictId);
            //dict.setHasChildren(isChild);
            if (isChild) {
                dict.setHasChildren(isChild);
            }
        }
        return dicts;
    }

    private boolean findIsChild(Long dictId) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id", dictId);
        Integer count = baseMapper.selectCount(wrapper);
        return count > 0;
    }

    @Override
    public void exportDictData(HttpServletResponse response) {
        try {
            //设置下载文件的mime类型 让浏览器认识,浏览器只认mime类型
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            //处理中文乱码
            String fileName = URLEncoder.encode("数据字典", "utf-8");
            //设置响应头:无论什么类型文件都下载方式打开
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            //查询数据库得到所有数据字典
            List<Dict> dictList = baseMapper.selectList(null);

            ArrayList<DictEeVo> dictVoList = new ArrayList<>();
            //集合中的Dict->DictEeVo
            for (int i = 0; i < dictList.size(); i++) {
                Dict dict = dictList.get(i);
                DictEeVo dictEeVo = new DictEeVo();
//                dictEeVo.setId(dict.getId());
//                dictEeVo.setName(dict.getName());
//                dictEeVo.setDictCode(dict.getDictCode());
//                dictEeVo.setParentId(dict.getParentId());
//                dictEeVo.setValue(dict.getValue());
                BeanUtils.copyProperties(dict, dictEeVo);
                //放到集合中
                dictVoList.add(dictEeVo);
            }

            //调用easyexcel方法写操作
            EasyExcel.write(response.getOutputStream(), DictEeVo.class)
                    .sheet("数据字典").doWrite(dictVoList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //导入
    @Override
    //把上传过来文件内容获取出来，添加到数据库
    public void importDictData(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream(), DictEeVo.class, dictListener).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getNameByDictCodevalue(String dictCode, String value) {
        if (StringUtils.isEmpty(dictCode)) {
            //根据value值直接查询
            QueryWrapper<Dict> wrapperValue = new QueryWrapper<>();
            wrapperValue.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapperValue);
            if (dict != null) {
                return dict.getName();
            }
        } else {
            //数据库中存在相同value值,此时可进行如下操作
            //存在dictCode的数据只有那几个大分类如省.学历.证件类型.民族,这时就需要根据dictCode查询符合的数据(data),
            //再查询哪条数据的parent_id等于它(data)的id,且value值等于value
            Dict dictParent = this.getDictByDictCode(dictCode);
            //优化一下
            if (dictParent == null) {
                return null;
            }
            //获取上层id.根据上层id和value查询
            QueryWrapper<Dict> wrapperChild = new QueryWrapper<>();
            wrapperChild.eq("parent_id", dictParent.getId());
            wrapperChild.eq("value", value);
            Dict dict = baseMapper.selectOne(wrapperChild);
            return dict.getName();
        }
        return null;
    }

    //实现方法 根据dict_code查询
    private Dict getDictByDictCode(String dictCode) {
        QueryWrapper<Dict> wrapper = new QueryWrapper<>();
        wrapper.eq("dict_code", dictCode);
        Dict codeDict = baseMapper.selectOne(wrapper);
        return codeDict;
    }

    //查询所有数据 比如所有省,所有医院等级等等
    @Override
    public List<Dict> findDictCodeByAll(String dictCode) {
        //查询出id值
        Dict dictParent = this.getDictByDictCode(dictCode);
        if (dictParent == null) {
            return null;
        }
        List<Dict> list = this.findDataChild(dictParent.getId());
        return list;
    }
}
